package com.morningstar.qs.api.basic.util;

import java.util.Date;
import java.util.Properties;
import java.util.Set;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

public class MailTool {

	private static final Logger log = Logger.getLogger(MailTool.class);

	public boolean sendSingleTextMail(String smtp, String senderMail, String title, String content, Set<String> toAddress, Set<String> ccAddress) {
		Properties props = new Properties();
		props.put("mail.smtp.host", smtp);
		Session session = Session.getInstance(props, null);
		try {
			Message msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(senderMail));
			if (toAddress != null && toAddress.size()>0) {
				for (String toMail : toAddress) {
					msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
				}
			}
			if(ccAddress!=null && ccAddress.size()>0) {
				for(String ccMail : ccAddress) {
					log.info("Cc: "+ccMail);
					msg.addRecipient(Message.RecipientType.CC, new InternetAddress(ccMail));
				}
			}
			msg.setSubject(title);
			msg.setSentDate(new Date());
			msg.setText(content);
			Transport.send(msg);
		} catch (MessagingException mex) {
			mex.printStackTrace();
			Exception ex = mex;
			do {
				if (ex instanceof SendFailedException) {
					SendFailedException sfex = (SendFailedException) ex;
					Address[] invalid = sfex.getInvalidAddresses();
					if (invalid != null) {
						log.info("    ** Invalid Addresses");
						if (invalid != null) {
							for (int i = 0; i < invalid.length; ++i)
								log.info("         " + invalid[i]);
						}
					}
					Address[] validUnsent = sfex.getValidUnsentAddresses();
					if (validUnsent != null) {
						log.info("    ** ValidUnsent Addresses");
						if (validUnsent != null) {
							for (int i = 0; i < validUnsent.length; ++i)
								log.info("         " + validUnsent[i]);
						}
					}
					Address[] validSent = sfex.getValidSentAddresses();
					if (validSent != null) {
						log.info("    ** ValidSent Addresses");
						if (validSent != null) {
							for (int i = 0; i < validSent.length; ++i)
								log.info("         " + validSent[i]);
						}
					}
				}
				log.info("\n");
				if (ex instanceof MessagingException)
					ex = ((MessagingException) ex).getNextException();
				else
					ex = null;
			} while (ex != null);
		}

		return true;
	}


}
